import { login, getInfoAdmin, logout, clearCache, } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/token'

import router, { resetRouter } from '@/router'
import Layout from '@/layout'
import { Message } from 'element-ui'

// 默认值
const state = {
  token: getToken(),
  isAdmin: false,
  is_super: 0,
  adminInfo: {},
  routes: [],
  routes_btn: [],
}

// 设置
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_IS_ADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_IS_SUPER: (state, routes) => {
    state.is_super = routes
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_ROUTES_BTN: (state, routes) => {
    state.routes_btn = routes
  },
  SET_ADMIN_INFO: (state, admin_info) => {
    state.adminInfo = admin_info
  },
}

// 方法
const actions = {
  // 用户登录
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data).then(response => {
        commit('SET_TOKEN', response.login_key)
        setToken(response.login_key)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取管理员信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfoAdmin().then(response => {
        if (!Object.keys(response.admin_info).length) {
          reject('验证失败，请重新登录。')
        }

        // 无权限路由处理
        const routerList = response.router_list
        const noPermissionRouters = []
        const noPermissionRoutersChildren = []
        routerList.forEach((m, i) => {
          if (m.parent_id == '0') { // 最外层，没有父层的
            const module = {
              path: '/' + m.url,
              name: m.id,
              meta: {
                id: m.id,
                title: m.name,
                icon: m.image_src,
                fullPath: '/' + m.url
              }
            }
            noPermissionRouters.push(module)
          }
        })

        function convertTreeRouter(routers) { // 递归添加children
          routers.forEach(r => {
            routerList.forEach((m, i) => {
              if (m.parent_id && m.parent_id == r.meta.id) {
                if (!r.children) {
                  r.children = []
                }
                m.fullPath = r.meta.fullPath + '/' + m.url
                const menu = {
                  path: m.fullPath,
                  name: m.id,
                  component(resolve) {
                    require(['@/views' + r.meta.fullPath + '/' + m.url], resolve)
                  },
                  meta: {
                    id: m.id,
                    title: m.name,
                    icon: m.image_src,
                    fullPath: r.meta.fullPath + '/' + m.url
                  }
                }
                r.children.push(menu)
                noPermissionRoutersChildren.push(menu)
              }
            })
            if (r.children) {
              convertTreeRouter(r.children)
            }
          })
        }
        convertTreeRouter(noPermissionRouters)
        // 添加可访问路由
        router.addRoutes(noPermissionRoutersChildren)

        // 菜单处理
        const menuList = response.admin_info.menu_list
        const menuRouters = []
        menuList.forEach((m, i) => {
          if (m.parent_id == '0') { // 最外层，没有父层的
            const module = {
              path: '/' + m.url,
              component: Layout,
              name: m.id,
              meta: {
                id: m.id,
                title: m.name,
                icon: m.image_src,
                fullPath: '/' + m.url
              }
            }
            menuRouters.push(module)
          }
        })

        function convertTree(routers) { // 递归添加children
          routers.forEach(r => {
            menuList.forEach((m, i) => {
              if (m.parent_id && m.parent_id == r.meta.id) {
                if (!r.children) {
                  r.children = []
                }
                m.fullPath = r.meta.fullPath + '/' + m.url
                const menu = {
                  path: m.fullPath,
                  name: m.id,
                  component(resolve) {
                    require(['@/views' + r.meta.fullPath + '/' + m.url], resolve)
                  },
                  meta: {
                    id: m.id,
                    title: m.name,
                    icon: m.image_src,
                    fullPath: r.meta.fullPath + '/' + m.url
                  }
                }
                r.children.push(menu)
              }
            })
            if (r.children) {
              convertTree(r.children)
            }
          })
        }
        convertTree(menuRouters)
        // 添加可访问路由
        router.addRoutes(menuRouters)

        // 按钮权限处理
        const btnList = response.admin_info.btn_list
        const btnRouters = []
        const btnRoutersChildren = []
        btnList.forEach((m, i) => {
          if (m.parent_id == '0') { // 最外层，没有父层的
            const module = {
              fullPath: m.url,
              id: m.id
            }
            btnRouters.push(module)
          }
        })

        function convertTreeBtn(routers) { // 递归添加children
          routers.forEach(r => {
            btnList.forEach((m, i) => {
              if (m.parent_id && m.parent_id == r.id) {
                if (!r.children) {
                  r.children = []
                }
                m.fullPath = r.fullPath + '_' + m.url
                const menu = {
                  fullPath: m.fullPath,
                  id: m.id
                }
                r.children.push(menu)
                btnRoutersChildren.push(menu.fullPath)
              }
            })
            if (r.children) {
              convertTreeBtn(r.children)
            }
          })
        }
        convertTreeBtn(btnRouters)

        response.admin_info.menu_list = menuRouters
        response.admin_info.btn_list = btnRoutersChildren
        response.admin_info.avatar = '/img/admin_avatar.png'
        commit('SET_ROUTES', menuRouters)
        commit('SET_ROUTES_BTN', btnRoutersChildren)
        commit('SET_IS_ADMIN', true)
        commit('SET_IS_SUPER', response.admin_info.is_super)
        commit('SET_ADMIN_INFO', response.admin_info)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 删除服务器Token
      logout().then()

      commit('SET_TOKEN', '')
      commit('SET_IS_ADMIN', false)
      commit('SET_IS_SUPER', 0)
      commit('SET_ADMIN_INFO', {})
      commit('SET_ROUTES', [])
      commit('SET_ROUTES_BTN', [])
      removeToken()
      resetRouter()
      // 重置访问的视图和缓存的视图
      // dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // 删除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_IS_ADMIN', false)
      commit('SET_IS_SUPER', 0)
      commit('SET_ADMIN_INFO', {})
      commit('SET_ROUTES', [])
      commit('SET_ROUTES_BTN', [])
      removeToken()
      resolve()
    })
  },

  // 清除缓存
  clearCache() {
    return new Promise((resolve, reject) => {
      clearCache().then(() => {
        reject('清除缓存成功')
        Message({
          message: '清除缓存成功',
          type: 'success'
        })
      })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
